﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using UniumLocalNetGames.Net;

namespace UniumLocalNetGames.Net
{
    public class UniumLocalUdpServer
    {
        UdpClient client;
        IPEndPoint receiveport;
        static UniumLocalUdpChat Chat;
        private Thread listenThread;
        bool Check = false;
        public UniumLocalUdpServer(UniumLocalUdpChat chat)
        {
             Chat = chat;
            receiveport = new IPEndPoint(new IPAddress(0), (0));
 
        }

        public void StartListenAsync()
        {
            if (!Check)
            {
                listenThread = new Thread(Listen);
                listenThread.Start();
                Check = true;
            }
        }

        private void Listen()
        {
            try
            {
                client = new UdpClient(5000);
            }
            catch
            {
                MessageBox.Show("To program is also running\n");

            }

            byte[] data;
            string Data;
            while (true)
            {
               
                data = client.Receive(ref receiveport);
                Data = Convert.ToString(data);
                if (Data.Length < UniumLocalMessages.InviteMessage.Length || Data.Substring(0, UniumLocalMessages.InviteMessage.Length) != UniumLocalMessages.InviteMessage)
                    continue;
                else
                {
                    Data = Data.Substring(UniumLocalMessages.InviteMessage.Length);
                    var message = UniumLocalMessages.CheckMessage(Data);
                    if (message == null)
                        continue;
                    message.sender = receiveport;
                    Chat.NewMessage(message);
                }
            }
        }
    }
}
